// 主应用文件
const App = {
    // 应用配置
    config: {
        token: localStorage.getItem('token'),
        currentUser: null,
        unreadCounts: {
            accounts: {},  // 账户级别未读数
            folders: {}    // 文件夹级别未读数
        },
        syncFailedAccounts: [],  // 同步失败的账户列表
        lastClickedFolderId: null,
        lastClickTime: 0,
        isTouchDevice: false,  // 触摸屏设备标识
        currentOpenMenuAccountId: null,  // 当前打开的设置菜单对应的账户ID
        folderDblClickTimestamps: {}, // 用于跟踪文件夹双击时间
    },

    // 初始化应用
    init: function() {
        this.detectTouchDevice();  // 检测触摸设备
        this.bindEvents();
        this.checkAuthStatus();
        // setupWebSocket 将在 loadAccountFolders 完成后调用
        EmailModule.init();
        LayoutManager.init(); // 初始化布局管理器
    },

    // 检测触摸设备
    detectTouchDevice: function() {
        // 核心逻辑修改：仅在手机或平板上才认为是“触摸设备”
        const isTouch = DeviceDetector.isMobile() || DeviceDetector.isTablet();
    
        this.config.isTouchDevice = isTouch;
    
        if (isTouch) {
            $('body').addClass('touch-device');
        } else {
            $('body').removeClass('touch-device');
        }
        
        // 注册设备变化回调，动态更新触摸设备状态
        DeviceDetector.onChange((cache) => {
            const newIsTouch = cache.isMobile || cache.isTablet;
            if (this.config.isTouchDevice !== newIsTouch) {
                this.config.isTouchDevice = newIsTouch;
                
                if (newIsTouch) {
                    $('body').addClass('touch-device');
                    console.log('设备变更：已切换到触摸设备模式 (手机/平板)');
                } else {
                    $('body').removeClass('touch-device');
                    console.log('设备变更：已切换到非触摸设备模式 (PC)');
                }
            }
        });
    
        return isTouch;
    },

    // 绑定事件
    bindEvents: function() {
        // 使用事件委托处理动态生成的菜单项
        $(document).on('click', '[data-menu-action]', function() {
            const action = $(this).data('menu-action');
            switch (action) {
                case 'logout':
                    Api.handleLogout();
                    break;
                case 'profile':
                    AccountModule.loadProfile();
                    break;
                case 'mfa-settings':
                    if (App.config.currentUser.is_mfa_enabled) {
                        AccountModule.showDisableMfaModal();
                    } else {
                        AccountModule.showSetupMfaModal();
                    }
                    break;
                case 'webauthn-settings':
                    if (App.config.currentUser.is_webauthn_enabled) {
                        AccountModule.showUnbindWebAuthnModal();
                    } else {
                        AccountModule.showBindWebAuthnModal();
                    }
                    break;
                case 'notification-settings':
                    NotificationManager.showSettingsPanel();
                    break;
                case 'proxy-settings':
                    ProxyModule.showProxyManagement();
                    break;
                case 'translation-settings':
                    TranslationSettings.openModal();
                    break;
                case 'admin-users':
                    if (DeviceDetector.isMobile()) {
                        window.location.href = 'admin-users.html';
                    } else {
                        layui.layer.open({
                            type: 2,
                            title: '账号管理',
                            area: ['100%', '100%'],
                            content: 'admin-users.html',
                            maxmin: true
                        });
                    }
                    break;
            }
        });
        $('#add-account-btn').on('click', () => AccountModule.loadAddAccount());

        // 折叠所有文件夹功能（使用事件委托）
        $(document).on('click', '#toggle-folders-btn', () => {
            const accountItems = $('.account-list-item');
            
            // 先折叠所有展开的自定义文件夹（通过模拟点击折叠按钮）
            accountItems.find('.folder-toggle-icon.layui-icon-down').each(function() {
                $(this).trigger('click');
            });
            
            // 再折叠所有账户
            accountItems.removeClass('expanded');
            accountItems.find('.account-folder-dl').slideUp(200);
            accountItems.find('.toggle-icon-wrapper .layui-icon')
                .removeClass('layui-icon-down')
                .addClass('layui-icon-right');
        });

        const list = $('#account-folder-list');
        // 处理折叠按钮的点击
        list.on('click', '.toggle-icon-wrapper', function(e) {
            e.stopPropagation();
            
            const listItem = $(this).closest('.account-list-item');
            const toggleIcon = $(this).find('.layui-icon');
            
            // 只切换折叠状态，不选中任何文件夹
            toggleIcon.toggleClass('layui-icon-right layui-icon-down');
            listItem.find('.account-folder-dl').slideToggle(200);
        });
        
        // 处理账户名称区域的点击
        list.on('click', '.account-info-wrapper', function(e) {
            // 如果点击的是设置图标或其内部元素，或者是拖拽手柄，则不执行操作
            if ($(e.target).closest('.settings-icon-wrapper').length ||
                $(e.target).closest('.drag-handle-wrapper').length) {
                e.preventDefault();
                e.stopPropagation();
                return;
            }
            e.stopPropagation();

            const listItem = $(this).closest('.account-list-item');
            const toggleIcon = listItem.find('.toggle-icon-wrapper .layui-icon');
            
            // 切换折叠状态
            toggleIcon.toggleClass('layui-icon-right layui-icon-down');
            listItem.find('.account-folder-dl').slideToggle(200);
        });

        // 单独处理设置图标的点击
        list.on('click', '.settings-icon-wrapper', function(e) {
            e.preventDefault(); // 阻止默认行为
            e.stopPropagation(); // 阻止事件冒泡
            e.stopImmediatePropagation(); // 阻止同一元素上的其他事件处理器
            
            const accountId = $(this).data('account-id');

            // 如果点击的是同一个账户的设置按钮，则关闭菜单
            if (App.config.currentOpenMenuAccountId === accountId) {
                App.config.currentOpenMenuAccountId = null;
                return; // 不调用showAccountSettings，让菜单自动关闭
            }

            // 打开新菜单并记录账户ID
            App.config.currentOpenMenuAccountId = accountId;
            AccountModule.showAccountSettings(accountId, this);
        });

        // 右键菜单事件
        list.on('contextmenu', '.account-info-wrapper', function(e) {
            e.preventDefault();
            // 触发设置图标的点击事件，以显示菜单
            $(this).closest('.account-list-item').find('.settings-icon-wrapper').trigger('click');
        });
    },

    // 检查认证状态
    checkAuthStatus: function() {
        const token = this.config.token;
        if (!token) {
            if (!window.location.pathname.endsWith('login.html')) {
                window.location.href = 'login.html';
            }
            return;
        }

        this.getCurrentUser().then(async user => {
            if (user) {
                this.config.currentUser = user;
                $('#username-display').text(user.username);
                $('.layui-nav-img').attr('src', user.avatar || 'images/user-avatar.png');
                
                // 动态渲染用户菜单
                this.renderUserMenu(user);

                await this.loadAccountFolders(); // 等待账户文件夹加载完成
                // 账户文件夹加载完成后再建立WebSocket连接，确保DOM已渲染
                this.setupWebSocket();
            } else {
                Api.handleLogout();
            }
        }).catch(() => Api.handleLogout());
    },

    // 获取当前用户信息（使用Api的缓存方法）
    getCurrentUser: async function() {
        try {
            return await Api.getCurrentUser();
        } catch (error) {
            return null;
        }
    },

    // 递归渲染文件夹
    renderFolders: function(folders, accountId, level = 0) {
        let html = '';
        if (!folders || folders.length === 0) {
            return html;
        }
    
        const folderIconMap = {
            'INBOX': 'layui-icon-email',
            'UNREAD': 'layui-icon-dialogue',
            'Drafts': 'layui-icon-edit',  // 系统草稿箱
            'Sent': 'layui-icon-release',
            'Junk': 'layui-icon-fonts-clear',
            'Trash': 'layui-icon-delete',
            // 添加更多自定义文件夹图标
        };
    
        folders.forEach(folder => {
            const hasChildren = folder.children && folder.children.length > 0;
            const displayName = folder.display_name;
            const folderName = folder.name;
            const paddingLeft = 20; // 固定缩进20px
            
            const iconClass = folderIconMap[folderName] || 'layui-icon-folder';
            
            // 自定义文件夹判断（不包括固定文件夹，包含系统草稿箱Drafts）
            const isCustomFolder = !['INBOX', 'UNREAD', 'Drafts', 'Sent', 'Junk', 'Trash'].includes(folderName);
            
            // 生成文件夹未读徽标ID
            // UNREAD虚拟文件夹使用简单ID，其他文件夹使用base64编码确保唯一性
            const badgeId = folderName === 'UNREAD' 
                ? `folder-unread-badge-${accountId}-UNREAD`
                : `folder-unread-badge-${accountId}-${btoa(encodeURIComponent(folderName)).replace(/[^a-zA-Z0-9]/g, '_')}`;
    
            html += `
                <dd style="padding-left: ${paddingLeft}px;" class="folder-item">
                    <div class="folder-item-container">
                        <div class="folder-column folder-toggle">
                            ${hasChildren ? '<i class="layui-icon layui-icon-right folder-toggle-icon"></i>' : ''}
                        </div>
                        <div class="folder-column folder-icon">
                            <i class="layui-icon ${iconClass}"></i>
                        </div>
                        <a href="javascript:void(0);"
                           class="folder-column folder-link"
                           data-account-id="${accountId}"
                           data-folder-name="${folderName}">
                           ${displayName}
                           <span class="layui-badge" id="${badgeId}" style="display: none; margin-left: 5px;">0</span>
                        </a>
                        <div class="folder-column folder-actions">
                            ${isCustomFolder ? '<i class="layui-icon layui-icon-set folder-settings-icon" title="设置"></i>' : ''}
                        </div>
                    </div>
                    ${hasChildren ? `<dl class="sub-folder-dl" style="display: none;">${this.renderFolders(folder.children, accountId, level + 1)}</dl>` : ''}
                </dd>
            `;
        });
        return html;
    },

    // 加载账户和文件夹列表
    loadAccountFolders: async function() {
        try {
            // 批量获取账户列表和所有文件夹
            const accounts = await Api.apiRequest('/email-accounts');
            const allFolders = await Api.apiRequest('/email-accounts/folders');

            // 更新 EmailModule 的缓存
            EmailModule.cache.accounts = accounts;
            const container = $('#account-folder-list');
            container.html('');
            const lastOpened = JSON.parse(localStorage.getItem('lastOpenedFolder'));

            for (let i = 0; i < accounts.length; i++) {
                const account = accounts[i];
                // JSON 对象的键总是字符串，需要转换
                const folders = allFolders[account.id.toString()] || [];
                let isExpanded = false;
                let isSelected = false;

                if (lastOpened) {
                    if (account.id === lastOpened.accountId) {
                        isExpanded = true;
                        isSelected = true;
                    }
                } else if (i === 0) {
                    isExpanded = true;
                    isSelected = true;
                }

                // 从缓存中获取未读数（将通过 WebSocket 实时更新）
                const unreadCount = this.config.unreadCounts.accounts[account.id] || 0;
                const foldersHtml = this.renderFolders(folders, account.id);

                const listItem = $(`
                    <li class="account-list-item ${isExpanded ? 'expanded' : ''} ${isSelected ? 'selected' : ''}" data-account-id="${account.id}">
                        <div class="account-item-main">
                            <div class="toggle-icon-wrapper">
                                <i class="layui-icon ${isExpanded ? 'layui-icon-down' : 'layui-icon-right'}"></i>
                            </div>
                            <a href="javascript:;" class="account-info-wrapper">
                                <span class="account-display">
                                    <span class="account-name">
                                        ${account.name || account.email}
                                        <span class="layui-badge" id="unread-badge-${account.id}" style="${unreadCount > 0 ? '' : 'display: none;'}">${unreadCount}</span>
                                        <span class="layui-badge layui-bg-orange" id="sync-failed-badge-${account.id}" style="display: none;">!</span>
                                        ${!account.is_active ? '<i class="layui-icon layui-icon-disabled" style="color: #4f4f4f; font-size: 14px; margin-left: 5px;" title="已禁用"></i>' : ''}
                                    </span>
                                    ${account.name ? `<small class="account-email">${account.email}</small>` : ''}
                                </span>
                            </a>
                            <div class="drag-handle-wrapper" data-account-id="${account.id}" title="拖拽排序">
                                <i class="layui-icon layui-icon-slider"></i>
                            </div>
                            <div class="settings-icon-wrapper" data-account-id="${account.id}">
                                <i class="layui-icon layui-icon-set"></i>
                            </div>
                        </div>
                        <dl class="account-folder-dl" style="${isExpanded ? 'display: block;' : 'display: none;'}">
                            ${foldersHtml}
                        </dl>
                    </li>
                `);
                container.append(listItem);
            }

            this.initSortable();
            
            // 绑定事件
            this.bindFolderEvents();

            if (lastOpened) {
                // 查找对应的文件夹链接
                const targetFolderLink = $(`a.folder-link[data-account-id='${lastOpened.accountId}'][data-folder-name='${lastOpened.folder}']`);
                if (targetFolderLink.length > 0) {
                    // 展开所有父级文件夹
                    targetFolderLink.parents('.sub-folder-dl').show().each(function() {
                        $(this).prev('.folder-item-container').find('.folder-toggle-icon')
                            .removeClass('layui-icon-right').addClass('layui-icon-down');
                    });
                    
                    // 触发点击事件来加载邮件列表并设置选中状态
                    // 确保click事件能正确触发邮件加载和UI更新
                    targetFolderLink.trigger('click');
                } else {
                    // 如果找不到特定文件夹，就加载账户的默认文件夹
                    EmailModule.loadEmailList('INBOX', lastOpened.accountId, false);
                }
            } else {
                // 如果没有 lastOpened，默认加载第一个账户的INBOX
                const firstAccount = accounts[0];
                if(firstAccount) {
                    EmailModule.loadEmailList('INBOX', firstAccount.id, false);
                }
            }

        } catch (error) {
            console.error('加载邮箱账户或文件夹失败:', error);
        }
    },

    // 绑定文件夹相关事件
    bindFolderEvents: function() {
        const listContainer = $('#account-folder-list');
        
        // 统一处理文件夹点击事件（智能防抖：第一次加载，1秒内再次点击则折叠/展开）
        listContainer.off('click', '.folder-link').on('click', '.folder-link', function(e) {
            e.stopPropagation(); // 阻止事件冒泡
        
            const $this = $(this);
            const accountId = $this.data('account-id');
            const folderName = $this.data('folder-name');
            const key = `${accountId}-${folderName}`;
            const now = Date.now();
            
            // 获取上次点击时间
            const lastClick = App.config.folderDblClickTimestamps[key] || 0;
            const timeDiff = now - lastClick;
            
            // 如果在500ms内再次点击同一文件夹，则只展开/折叠，不重新加载邮件列表
            if (timeDiff < 500 && timeDiff > 0) {
                // 检查是否有折叠图标
                const $folderItem = $this.closest('.folder-item');
                const toggleIcon = $folderItem.find('.folder-toggle-icon').first();
                
                if (toggleIcon.length > 0) {
                    toggleIcon.trigger('click');
                }
                
                return; // 不执行后续的加载邮件列表操作
            }
            
            // 更新时间戳
            App.config.folderDblClickTimestamps[key] = now;
            
            // 移除所有账户和文件夹的选中状态
            $('#account-folder-list .selected').removeClass('selected');
        
            // 为当前点击的文件夹的父级 <dd> 添加 'selected' 类
            $this.closest('dd.folder-item').addClass('selected');
        
            // 同时选中对应的账户项
            $this.closest('.account-list-item').addClass('selected');
        
            // 移动端/平板端：点击文件夹后自动关闭账户列表
            if ((LayoutManager.state.isMobile || LayoutManager.state.isTablet) && LayoutManager.state.mobileMenuOpen) {
                LayoutManager.closeMobileMenu();
            }
        
            // 保存最后点击的文件夹信息到localStorage
            localStorage.setItem('lastOpenedFolder', JSON.stringify({
                accountId: accountId,
                folder: folderName
            }));
        
            EmailModule.loadEmailList(folderName, accountId, false, $this[0]);
        });

        // 为新的层级文件夹绑定折叠/展开事件
        listContainer.off('click', '.folder-toggle-icon').on('click', '.folder-toggle-icon', function(e) {
            e.stopPropagation();
            
            const $toggleIcon = $(this);
            const $folderItem = $toggleIcon.closest('dd.folder-item');
            const $folderLink = $folderItem.find('.folder-link').first();
            const accountId = $folderLink.data('account-id');
            const folderName = $folderLink.data('folder-name');
            const isExpanding = $toggleIcon.hasClass('layui-icon-right'); // 当前是否要展开
            
            // 切换图标
            $toggleIcon.toggleClass('layui-icon-right layui-icon-down');
            $folderItem.find('.sub-folder-dl').first().slideToggle(200);

            // 切换文件夹打开/关闭图标
            const folderIcon = $toggleIcon.closest('.folder-item-container').find('.folder-icon .layui-icon');
            if (folderIcon.hasClass('layui-icon-folder') || folderIcon.hasClass('layui-icon-folder-open')) {
                folderIcon.toggleClass('layui-icon-folder layui-icon-folder-open');
            }
            
            // 更新父文件夹徽标
            App.updateFolderBadgeOnToggle(accountId, folderName, isExpanding);
        });

        // 点击文件夹图标也能选中
        listContainer.off('click', '.folder-icon').on('click', '.folder-icon', function(e) {
            e.stopPropagation();
            // 模拟点击文字链接
            $(this).siblings('.folder-link').trigger('click');
        });

        // 为文件夹设置图标绑定事件
        listContainer.off('click', '.folder-settings-icon').on('click', '.folder-settings-icon', function(e) {
            e.stopPropagation();
            e.preventDefault();
            const folderItem = $(this).closest('.folder-item-container');
            const folderLink = folderItem.find('.folder-link');
            const accountId = folderLink.data('account-id');
            const folderName = folderLink.data('folder-name');
            App.showFolderSettings(this, accountId, folderName);
        });
        
        // 右键/长按 整个文件夹项 触发菜单
        listContainer.off('contextmenu', '.folder-item-container').on('contextmenu', '.folder-item-container', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const settingsIcon = $(this).find('.folder-settings-icon');
            if (settingsIcon.length) {
                // 模拟点击设置图标来显示菜单
                settingsIcon.trigger('click');
            }
        });

    },
    
    // 显示自定义文件夹的设置菜单
    showFolderSettings: function(element, accountId, folderName) {
        layui.dropdown.render({
            elem: element,
            show: true,
            data: [
                { title: '添加子文件夹', id: 'add' },
                { title: '重命名', id: 'rename' },
                { title: '删除', id: 'delete' }
            ],
            click: function(data) {
                switch (data.id) {
                    case 'add':
                        AccountModule.createFolder(accountId, folderName);
                        break;
                    case 'rename':
                        AccountModule.renameFolder(accountId, folderName);
                        break;
                    case 'delete':
                        App.deleteFolder(accountId, folderName);
                        break;
                }
            },
            // 确保菜单在触摸设备上也能正常显示
            trigger: App.config.isTouchDevice ? 'click' : 'hover',
            done: function() {
                // 菜单关闭后不需要执行任何特殊操作，但保留done回调是好的实践
            }
        });
    },

    // 初始化拖拽排序
    initSortable: function() {
        const el = $('#account-folder-list');
        if (el.data('sortable')) {
            el.data('sortable').destroy();
        }
        
        // 记录拖拽前的顺序
        let originalOrder = [];
        
        const sortable = new Sortable(el[0], {
            animation: 150,
            handle: '.drag-handle-wrapper',  // 只能通过拖拽手柄进行拖拽

            onStart: (evt) => {
                // 记录拖拽前的账户顺序
                originalOrder = el.find('.account-list-item').map(function() {
                    return $(this).data('account-id');
                }).get();
            },

            onEnd: (evt) => {
                // 获取拖拽后的账户顺序
                const newOrder = el.find('.account-list-item').map(function() {
                    return $(this).data('account-id');
                }).get();
                
                // 比较顺序是否发生变化
                const orderChanged = originalOrder.length !== newOrder.length ||
                    originalOrder.some((id, index) => id !== newOrder[index]);
                
                // 只有顺序发生变化时才更新
                if (orderChanged) {
                    this.updateAccountOrder(newOrder);
                }
            }
        });
        el.data('sortable', sortable);
    },

    // 计算文件夹的累加未读数（包括所有子文件夹）
    calculateFolderUnreadCount: function(accountId, folderName, foldersData) {
        if (!foldersData || !foldersData[accountId]) return 0;
        
        const accountFolders = foldersData[accountId];
        let totalCount = accountFolders[folderName] || 0;
        
        // 累加所有子文件夹的未读数
        const prefix = folderName + '/';
        for (const fname in accountFolders) {
            if (fname.startsWith(prefix)) {
                totalCount += accountFolders[fname] || 0;
            }
        }
        
        return totalCount;
    },

    // 统一更新所有未读徽标（账户徽标 + 所有文件夹徽标）
    updateAllUnreadBadges: function() {
        const folders = this.config.unreadCounts.folders;
        const accounts = this.config.unreadCounts.accounts;
        
        if (!accounts || !folders) {
            console.warn('[徽标更新] 未读数据不完整');
            return;
        }
        
        // 遍历所有账户
        for (const accountId in accounts) {
            const accountCount = accounts[accountId];
            const $accountItem = $(`.account-list-item[data-account-id="${accountId}"]`);
            
            if ($accountItem.length === 0) {
                console.warn(`[徽标更新] 未找到账户 ${accountId} 的DOM元素`);
                continue;
            }
            
            // 1. 更新账户徽标
            const accountBadge = $accountItem.find(`#unread-badge-${accountId}`);
            if (accountBadge.length) {
                if (accountCount > 0) {
                    accountBadge.text(accountCount).show();
                } else {
                    accountBadge.hide();
                }
            }
            
            // 2. 先隐藏该账户下所有文件夹徽标
            $accountItem.find('.layui-badge[id^="folder-unread-badge-"]').hide();
            
            // 3. 收集该账户下所有存在于DOM中的文件夹（包括父文件夹）
            const allFolderLinks = $accountItem.find('.folder-link');
            const accountFolders = folders[accountId] || {};
            
            // 遍历DOM中的所有文件夹，而不只是遍历有数据的文件夹
            allFolderLinks.each((index, element) => {
                const $folderLink = $(element);
                const folderName = $folderLink.data('folder-name');
                const rawCount = accountFolders[folderName] || 0; // 原始未读数（可能为0）
                
                // 生成徽标ID
                const badgeId = folderName === 'UNREAD'
                    ? `folder-unread-badge-${accountId}-UNREAD`
                    : `folder-unread-badge-${accountId}-${btoa(encodeURIComponent(folderName)).replace(/[^a-zA-Z0-9]/g, '_')}`;
                
                const badge = $folderLink.find(`#${badgeId}`);
                
                if (!badge.length) {
                    console.warn(`[徽标更新] 未找到文件夹 ${folderName} 的徽标元素: #${badgeId}`);
                    return; // continue
                }
                
                // 查找该文件夹对应的折叠图标，判断是否已展开
                const $folderItem = $folderLink.closest('.folder-item');
                const $toggleIcon = $folderItem.find('.folder-toggle-icon').first();
                
                // 判断展开状态
                const hasToggleIcon = $toggleIcon.length > 0;
                const isExpanded = hasToggleIcon && $toggleIcon.hasClass('layui-icon-down');
                
                // 根据展开状态决定显示原始数还是累加数
                let displayCount;
                if (isExpanded) {
                    // 已展开：只显示自己的未读数
                    displayCount = rawCount;
                } else {
                    // 已折叠或无子文件夹：显示累加未读数（包括所有子文件夹）
                    displayCount = this.calculateFolderUnreadCount(accountId, folderName, folders);
                }
                
                if (displayCount > 0) {
                    badge.text(displayCount).show();
                }
            });
        }
    },
    
    // 更新文件夹徽标（展开/折叠时调用）
    updateFolderBadgeOnToggle: function(accountId, folderName, isExpanding) {
        const folders = this.config.unreadCounts.folders;
        if (!folders || !folders[accountId]) return;
        
        const accountFolders = folders[accountId];
        const rawCount = accountFolders[folderName] || 0; // 原始未读数（只包含自己的）
        
        // 生成徽标ID
        const badgeId = folderName === 'UNREAD'
            ? `folder-unread-badge-${accountId}-UNREAD`
            : `folder-unread-badge-${accountId}-${btoa(encodeURIComponent(folderName)).replace(/[^a-zA-Z0-9]/g, '_')}`;
        
        const badge = $(`#${badgeId}`);
        
        if (!badge.length) {
            return;
        }
        
        if (isExpanding) {
            // 展开时：显示文件夹自己的真实未读数（不包括子文件夹）
            if (rawCount > 0) {
                badge.text(rawCount).show();
            } else {
                badge.hide();
            }
        } else {
            // 折叠时：显示累加后的未读数（包括所有子文件夹）
            const cumulativeCount = this.calculateFolderUnreadCount(accountId, folderName, folders);
            if (cumulativeCount > 0) {
                badge.text(cumulativeCount).show();
            } else {
                badge.hide();
            }
        }
    },

    // 更新同步失败徽标
    updateSyncFailedBadges: function() {
        const failedAccounts = this.config.syncFailedAccounts || [];
        
        // 首先隐藏所有同步失败徽标
        $('.layui-badge[id^="sync-failed-badge-"]').hide();
        
        // 显示同步失败的账户徽标
        failedAccounts.forEach(account => {
            const badge = $(`#sync-failed-badge-${account.id}`);
            if (badge.length) {
                badge.show();
            }
        });
    },

    // 更新账户排序
    updateAccountOrder: async function(accountIds) {
        try {
            await Api.apiRequest('/email-accounts/order', {
                method: 'PUT',
                body: JSON.stringify({ account_ids: accountIds })
            });
            layui.layer.msg('排序已更新', { icon: 1 });
            // 排序成功后不重新加载，保持当前状态
        } catch (error) {
            layui.layer.msg('排序更新失败', { icon: 2 });
            console.error('更新账户排序失败:', error);
            // 只在失败时才重新加载以恢复原有顺序
            this.loadAccountFolders();
        }
    },

    // 加- 邮件列表
    loadEmailList: async function(folder, accountId) {
        EmailModule.loadEmailList(folder, accountId);
    },

    deleteFolder: async function(accountId, folderName) {
        const folderLink = $(`.folder-link[data-account-id="${accountId}"][data-folder-name="${folderName}"]`);
        const wasSelected = folderLink.closest('.folder-item').hasClass('selected');

        layer.confirm('确定要删除该文件夹吗？此操作不可恢复。', {
            title: '确认删除',
            icon: 3
        }, async (index) => {
            layer.close(index);
            
            // 显示loading
            const loadingIndex = layer.load(1, { shade: [0.3, '#fff'] });
            
            try {
                await Api.apiRequest(`/email-accounts/${accountId}/folders`, {
                    method: 'DELETE',
                    body: JSON.stringify({ folder_name: String(folderName) })
                });
                layer.close(loadingIndex);
                layer.msg('文件夹删除成功', { icon: 1 });

                // 如果删除的是当前选中的文件夹，则刷新后选中INBOX
                const folderToSelectAfterDelete = wasSelected ? 'INBOX' : null;
                this.refreshAccountFolders(accountId, folderToSelectAfterDelete, null);
                
                // 通过WebSocket请求后端刷新未读数和同步失败状态
                if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                    this.ws.send(JSON.stringify({
                        action: 'refresh_unread_counts'
                    }));
                    this.ws.send(JSON.stringify({
                        action: 'refresh_sync_failed'
                    }));
                    console.log('已发送未读数和同步失败状态刷新请求');
                }
            } catch (error) {
                layer.close(loadingIndex);
                console.error('删除文件夹失败:', error);
                layer.msg(error.message || '删除文件夹失败', { icon: 2 });
            }
        });
    },

    // 渲染邮件列表
    renderEmailList: function(emails, folder) {
        const container = $('#email-list-container');
        const detailContainer = $('#email-detail-container');
        const iframe = detailContainer.find('#email-content-iframe');
        const placeholder = detailContainer.find('.placeholder');
        
        iframe.hide();
        placeholder.show();

        if (!emails || emails.length === 0) {
            container.html(`<div class="placeholder">没有邮件</div>`);
            return;
        }
        
        const emailList = $('<div class="email-list"></div>');
        emails.forEach(email => {
            const senderInfo = formatSender(email.sender);
            const displaySender = senderInfo.name || senderInfo.address;
            
            const item = $(`
                <div class="email-item ${!email.is_read ? 'unread' : ''}" onclick="App.viewEmail(${email.email_account_id}, ${email.id}, this)">
                    <div class="email-item-header">
                        <div class="email-sender" title="${escapeHtml(email.sender)}">${escapeHtml(displaySender)}</div>
                        <div class="email-time">${new Date(email.received_date).toLocaleString()}</div>
                    </div>
                    <div class="email-subject">${escapeHtml(email.subject)}</div>
                    <div class="email-preview">${escapeHtml(email.body_text?.substring(0, 100)) || '无内容预览'}</div>
                </div>
            `);
            emailList.append(item);
        });
        container.html(emailList);
    },

    // 查看邮件详情
    viewEmail: async function(accountId, emailId, element) {
        $('.email-item.selected').removeClass('selected');
        $(element).addClass('selected');
        try {
            const email = await Api.apiRequest(`/email-accounts/${accountId}/emails/${emailId}`);
            this.renderEmailDetail(email);
        } catch (error) {
            $('#email-detail-container').html('<div class="placeholder">加载邮件失败</div>');
        }
    },

    // 渲染邮件详情
    renderEmailDetail: function(email) {
        const detailContainer = $('#email-detail-container');
        const iframe = detailContainer.find('#email-content-iframe');
        const placeholder = detailContainer.find('.placeholder');
        
        const senderInfo = formatSender(email.sender);
        const displaySender = senderInfo.address 
            ? `${escapeHtml(senderInfo.name)} <${escapeHtml(senderInfo.address)}>`
            : escapeHtml(senderInfo.name);

        const emailContentHtml = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <style>
                    body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
                    .email-detail-header { border-bottom: 1px solid #eee; padding-bottom: 15px; margin-bottom: 15px; }
                    .email-detail-subject { font-size: 22px; margin: 0 0 10px; }
                    .email-detail-meta p { margin: 2px 0; color: #666; }
                    .email-detail-content { margin-top: 20px; }
                </style>
            </head>
            <body>
                <div class="email-detail-header">
                    <h2 class="email-detail-subject">${escapeHtml(email.subject)}</h2>
                    <div class="email-detail-meta">
                        <p><strong>发件人:</strong> ${displaySender}</p>
                        <p><strong>收件人:</strong> ${escapeHtml(email.to) || '未知'}</p>
                        <p><strong>时间:</strong> ${new Date(email.received_date).toLocaleString()}</p>
                    </div>
                </div>
                <div class="email-detail-content">${email.body_html || (escapeHtml(email.body_text) || '').replace(/\n/g, '<br>') || '无邮件内容'}</div>
            </body>
            </html>
        `;

        iframe.prop('srcdoc', emailContentHtml);
        placeholder.hide();
        iframe.show();
    },

    // 设置WebSocket连接
    setupWebSocket: function() {
        const token = localStorage.getItem('token'); // 始终从localStorage获取最新token
        if (!token) return;

        // 如果已有连接，先关闭
        if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
            this.ws.close();
        }

        const protocol = window.location.protocol === "https:" ? "wss" : "ws";
        const wsUrl = `${protocol}://${location.host}/ws/sync?token=${token}`;
        this.ws = new WebSocket(wsUrl);

        this.ws.onopen = () => {
            console.log('WebSocket 连接已建立');
        };

        this.ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                switch (data.status) {
                    case 'sync_success':
                        // sync_success 消息只更新未读数徽标，不显示通知，不自动刷新列表
                        console.log(`账户 ${data.accountId} 同步完成，新邮件数: ${data.newMailCount || 0}`);
                        break;
                    case 'unread_count_update':
                        // 更新缓存
                        if (data.counts.accounts) {
                            App.config.unreadCounts.accounts = data.counts.accounts;
                        }
                        if (data.counts.folders) {
                            App.config.unreadCounts.folders = data.counts.folders;
                        }
                        
                        // 统一更新所有徽标
                        App.updateAllUnreadBadges();
                        break;
                    case 'sync_failed_update':
                        // 更新同步失败账户缓存
                        App.config.syncFailedAccounts = data.failed_accounts || [];
                        
                        // 更新同步失败徽标
                        App.updateSyncFailedBadges();
                        break;
                    case 'retoken':
                        // 收到token续期消息
                        if (data.token) {
                            const oldToken = localStorage.getItem('token');
                            localStorage.setItem('token', data.token);
                            console.log('Token已通过WebSocket更新，准备重连WebSocket');
                            
                            // 需要重连WebSocket以使用新token
                            // 标记为主动断开，避免自动重连逻辑干扰
                            this.wsManualClose = true;
                            
                            // 关闭当前连接
                            if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
                                this.ws.close();
                            }
                            
                            // 等待旧连接完全关闭后使用新token重连
                            setTimeout(() => {
                                this.wsManualClose = false;
                                this.setupWebSocket();
                                console.log('WebSocket已使用新token重连');
                            }, 500);
                        }
                        break;
                    case 'sync_failed':
                        console.error('邮件同步失败通知:', data);
                        // 尝试从页面元素获取账户名称
                        const failedAccountItem = $(`.account-list-item[data-account-id='${data.accountId}']`);
                        const failedAccountName = failedAccountItem.length ? failedAccountItem.find('.account-name').clone().children().remove().end().text().trim() : `账户ID ${data.accountId}`;
                        // 提取错误信息的关键部分
                        const errorMsg = data.error || '未知错误';
                        layui.layer.msg(`邮箱【${failedAccountName}】后台同步失败<br>原因：${errorMsg}<br>请检查配置或稍后重试`, { icon: 2, time: 6000 });
                        break;
                    case 'heartbeat':
                        // console.log('收到心跳消息');
                        break;
                    case 'no_update':
                        // console.log('邮件检查完成，无更新');
                        break;
                    default:
                        break;
                }
            } catch (error) {
                console.error('处理WebSocket消息失败:', error);
            }
        };

        this.ws.onclose = () => {
            // 只在非主动断开时才自动重连
            if (!this.wsManualClose) {
                setTimeout(() => {
                    this.setupWebSocket();
                }, 5000);
            }
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
        };
    },

    // 刷新指定账户的文件夹列表
    refreshAccountFolders: async function(accountId, folderToSelect, triggerElement) {
        const $trigger = $(triggerElement);
        const $icon = $trigger ? $trigger.find('.layui-icon') : null;
        
        // 防止重复点击
        if ($trigger && $trigger.hasClass('refreshing')) {
            return;
        }
        
        if ($trigger && $icon) {
            $trigger.addClass('refreshing');
            $icon.addClass('layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop');
        }
        
        try {
            // 手动刷新时强制同步，从服务器获取最新文件夹列表
            const folders = await Api.apiRequest(`/email-accounts/${accountId}/folders?force_sync=true`);
            
            // 找到对应的账户项
            const $accountItem = $(`.account-list-item[data-account-id="${accountId}"]`);
            const $folderContainer = $accountItem.find('.account-folder-dl');
            
            // 记录当前展开的文件夹
            const expandedFolders = [];
            $folderContainer.find('.folder-toggle-icon.layui-icon-down').each(function() {
                const folderName = $(this).closest('.folder-item-container').find('.folder-link').data('folder-name');
                expandedFolders.push(folderName);
            });
            
            // 重新渲染文件夹
            const foldersHtml = this.renderFolders(folders, accountId);
            $folderContainer.html(foldersHtml);
            
            // 恢复之前展开的文件夹状态
            expandedFolders.forEach(folderName => {
                const $folderLink = $folderContainer.find(`.folder-link[data-folder-name="${folderName}"]`);
                if ($folderLink.length) {
                    const $container = $folderLink.closest('.folder-item-container');
                    $container.find('.folder-toggle-icon')
                        .removeClass('layui-icon-right')
                        .addClass('layui-icon-down');
                    $folderLink.closest('dd').find('.sub-folder-dl').first().show();
                }
            });
            
            // 恢复所有徽标
            this.updateAllUnreadBadges();
            this.updateSyncFailedBadges();
            
            // 重新绑定事件
            this.bindFolderEvents();
            
            // 如果指定了要选中的文件夹，则恢复选中状态
            if (folderToSelect) {
                const targetFolderLink = $folderContainer.find(`a.folder-link[data-folder-name='${folderToSelect}']`);
                if (targetFolderLink.length > 0) {
                    targetFolderLink.closest('dd.folder-item').addClass('selected');
                }
            }

            if (triggerElement) {
                layui.layer.msg('文件夹列表已刷新', { icon: 1, time: 1000 });
            }

        } catch (error) {
            console.error('刷新文件夹列表失败:', error);
            layui.layer.msg('刷新失败: ' + (error.detail || error.message), { icon: 2 });
        } finally {
            // 移除加载状态
            if ($trigger && $icon) {
                setTimeout(() => {
                    $trigger.removeClass('refreshing');
                    $icon.removeClass('layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop');
                }, 500);
            }
        }
    },

    // 渲染用户菜单
    renderUserMenu: function(user) {
        const menuContainer = $('#user-menu-dropdown');
        menuContainer.empty(); // 清空现有菜单项

        const menuItems = [
            { id: 'profile-btn', action: 'profile', text: '个人资料' },
            { id: 'mfa-settings-btn', action: 'mfa-settings', text: user.is_mfa_enabled ? '取消MFA' : '绑定MFA' },
            { id: 'webauthn-settings-btn', action: 'webauthn-settings', text: user.is_webauthn_enabled ? '解绑密钥' : '绑定密钥' },
            { type: 'divider' },
            { id: 'notification-settings-btn', action: 'notification-settings', text: '通知设置' },
            { id: 'proxy-settings-btn', action: 'proxy-settings', text: '代理管理' },
            { id: 'translation-settings-btn', action: 'translation-settings', text: '翻译设置' },
        ];

        if (user.is_admin) {
            menuItems.push({ type: 'divider' });
            menuItems.push({ id: 'admin-users-btn', action: 'admin-users', text: '账号管理' });
        }

        menuItems.push({ type: 'divider' });
        menuItems.push({ id: 'logout-btn', action: 'logout', text: '退出登录' });

        let menuHtml = '';
        menuItems.forEach(item => {
            if (item.type === 'divider') {
                menuHtml += '<dd><hr class="layui-nav-divider"></dd>';
            } else {
                menuHtml += `<dd><a href="javascript:;" id="${item.id}" data-menu-action="${item.action}">${item.text}</a></dd>`;
            }
        });

        menuContainer.html(menuHtml);
    }
};
